<template>
  <div class="login-form-wrapper">
    <a-tabs>
      <a-tab-pane key="1" title="账号密码登录">
        <!-- 账号密码登录 -->
        <div style="padding: 26px 40px">
          <a-form
            ref="loginForm"
            :model="userInfo"
            class="login-form"
            layout="vertical"
            @submit="handleSubmit"
          >
            <a-form-item
              field="userName"
              :rules="[{ required: true, message: '请输入登录账号' }]"
              :validate-trigger="['change', 'blur']"
              hide-label
            >
              <a-input
                class="inputHeight"
                v-model.trim="userInfo.userName"
                placeholder="请输入账号"
              >
                <template #prepend>
                  <img class="imgs" src="@/assets/login/login-33.png" alt="" />
                </template>
              </a-input>
            </a-form-item>

            <a-form-item
              field="passWord"
              :rules="[{ required: true, message: '请输入密码' }]"
              :validate-trigger="['change', 'blur']"
              hide-label
            >
              <a-input-password
                class="inputHeight"
                v-model.trim="userInfo.passWord"
                placeholder="请输入密码"
                allow-clear
                ><template #prepend>
                  <img class="imgs" src="@/assets/login/login-11.png" alt=""
                /></template>
              </a-input-password>
            </a-form-item>

            <a-form-item
              field="captcha"
              :rules="[{ required: true, message: '请输入验证码' }]"
              :validate-trigger="['change', 'blur']"
              hide-label
            >
              <a-input
                class="inputHeight"
                v-model.trim="userInfo.captcha"
                placeholder="请输入验证码"
                allow-clear
              >
                <template #append>
                  <img class="code" :src="state.codeUrl" alt="" @click="imgUrl" />
                </template>
                <template #prepend>
                  <img class="imgs" src="@/assets/login/login-22.png" alt=""
                /></template>
              </a-input>
            </a-form-item>
            <a-space :size="16" direction="vertical" style="margin-top: 10px">
              <a-button
                type="primary"
                style="
                  height: 40px;
                  border: 0px !important;
                  background: linear-gradient(to right, #3491fa, #9fd4fd);
                "
                html-type="submit"
                long
                :loading="state.loading"
              >
                立即登录
              </a-button>

              <a-button
                long
                style="
                  height: 40px;
                  border: 0px !important;
                  color: var(--color-neutral-10) !important;
                  background-color: var(--color-neutral-2) !important;
                "
                class="login-form-register-btn"
                @click="handleClick"
              >
                忘记密码
              </a-button>
            </a-space>
          </a-form>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" title="手机号码登录">
        <!-- 手机号码登录 -->
        <div style="padding: 20px 40px">
          <a-form
            ref="phoneInfo"
            :model="state.phoneInfo"
            class="login-form"
            layout="vertical"
            @submit="handleSubmit"
          >
            <a-form-item
              field="phone"
              :rules="[{ required: true, message: '请输入手机号码' }]"
              :validate-trigger="['change', 'blur']"
              hide-label
            >
              <a-input
                class="inputHeight"
                v-model.trim="state.phoneInfo.phone"
                placeholder="请输入手机号码"
              />
            </a-form-item>

            <a-form-item
              field="captcha"
              :rules="[{ required: true, message: '请输入验证码' }]"
              :validate-trigger="['change', 'blur']"
              hide-label
            >
              <a-input
                class="inputHeight"
                v-model="state.phoneInfo.captcha"
                placeholder="请输入验证码"
                allow-clear
              >
                <template #append>
                  <a-button
                    type="primary"
                    style="height: 40px; width: 100%"
                    :loading="sendCode.disable"
                    @click="send"
                    >{{ sendCode.codeText }}</a-button
                  >
                </template>
              </a-input>
            </a-form-item>
            <a-space :size="16" direction="vertical">
              <a-button
                style="
                  height: 40px;
                  border: 0px !important;
                  background: linear-gradient(to right, #3491fa, #9fd4fd);
                "
                type="primary"
                html-type="submit"
                long
                :loading="state.loading"
              >
                立即登录
              </a-button>
              <a-button
                long
                style="
                  height: 40px;
                  border: 0px !important;
                  color: var(--color-neutral-10) !important;
                  background-color: var(--color-neutral-2) !important;
                "
                class="login-form-register-btn"
                @click="handleClick"
              >
                忘记密码
              </a-button>
            </a-space>
          </a-form>
        </div>
      </a-tab-pane>
      <!-- <a-tab-pane key="3" title="扫码登录登录"> Content of Tab Panel 3 </a-tab-pane> -->
    </a-tabs>
  </div>
  <!-- 忘记密码 -->
  <a-modal v-model:visible="state.visible" width="40%" :footer="false" @before-close="beforeClose">
    <template #title> 忘记密码 </template>
    <div>
      <a-steps :current="state.current" label-placement="vertical" @change="setCurrent">
        <a-step description="输入账号信息">步骤一</a-step>
        <a-step description="确认新密码">步骤二</a-step>
        <a-step description="完成密码修改">步骤三</a-step>
      </a-steps>
      <div
        :style="{
          width: '100%',
          textAlign: 'center',
          background: 'var(--color-bg-2)',
          color: '#C2C7CC',
        }"
      >
        <div class="box">
          <div v-if="state.current == 1">
            <a-form ref="fotGot" :model="state.forGot" @submit="forgotNext">
              <a-form-item
                field="name"
                label="登录账号"
                :rules="[{ required: true, message: '请输入登录账号' }]"
                :validate-trigger="['change', 'blur']"
              >
                <a-input v-model="state.forGot.name" placeholder="please enter your username..." />
              </a-form-item>
              <a-form-item
                field="post"
                label="手机号码"
                :rules="[{ required: true, message: '请输入手机号' }]"
                :validate-trigger="['change', 'blur']"
              >
                <a-input v-model="state.forGot.post" placeholder="手机号码" />
              </a-form-item>
              <a-form-item
                field="codes"
                label="验证码"
                :rules="[{ required: true, message: '请输入验证码' }]"
                :validate-trigger="['change', 'blur']"
              >
                <a-input v-model="state.forGot.codes" placeholder="请输入验证码" allow-clear>
                  <template #append>
                    <a-button
                      type="primary"
                      style="width: 100%"
                      :loading="sendCode.disable"
                      @click="sends"
                      >{{ sendCode.codeText }}</a-button
                    >
                  </template>
                </a-input>
              </a-form-item>
              <a-form-item>
                <div style="width: 100%; display: flex; justify-content: center">
                  <a-button type="primary" html-type="submit">下一步</a-button>
                </div>
              </a-form-item>
            </a-form>
          </div>
          <div v-if="state.current == 2">
            <a-form :model="state.forGot" @submit="forgotNext">
              <a-form-item
                field="newPass"
                label="新密码"
                :rules="[{ required: true, message: '请输入新密码' }]"
                :validate-trigger="['change', 'blur']"
              >
                <a-input
                  v-model="state.forGot.newPass"
                  placeholder="please enter your username..."
                />
              </a-form-item>
              <a-form-item
                field="newPass1"
                label="确认密码"
                :rules="rules"
                :validate-trigger="['change', 'blur']"
              >
                <a-input v-model="state.forGot.newPass1" placeholder="手机号码" />
              </a-form-item>
              <a-form-item>
                <div style="width: 100%; display: flex; justify-content: space-around">
                  <a-button type="primary" @click="onPrev">上一步</a-button>
                  <a-button type="primary" html-type="submit">下一步</a-button>
                </div>
              </a-form-item>
            </a-form>
          </div>
          <div v-if="state.current == 3">
            <a-form :model="state.forGot" @submit="handleCancel">
              <a-form-item label="新密码">
                <a-input
                  v-model="state.forGot.newPass"
                  readonly
                  placeholder="please enter your username..."
                />
              </a-form-item>
              <a-form-item label="温馨提示">
                <a-input
                  v-model="state.forGot.Tips"
                  readonly
                  style="color: #3491fa"
                  placeholder="温馨提示"
                />
              </a-form-item>
              <a-form-item>
                <div style="width: 100%; display: flex; justify-content: space-around">
                  <a-button type="primary" :loading="loadings" html-type="submit">确认</a-button>
                </div>
              </a-form-item>
            </a-form>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'
  import { Message } from '@arco-design/web-vue'
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface'
  // import { useI18n } from 'vue-i18n'
  import { useStorage } from '@vueuse/core'
  // import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading'
  import { formpost } from '@/api/http'
  import { userLogin } from '@/api/url'
  import { UserState } from '@/store/types'
  import { randomString } from '@/utils'
  import useUserStore from '@/store/modules/user'

  import md5 from 'js-md5'
  // import type { LoginData } from '@/api/user';
  // import { toRaw } from '@vue/reactivity';

  const router = useRouter()
  // const { t } = useI18n()
  const fotGot = ref()
  const phoneInfo = ref()
  const errorMessage = ref('')
  const { loading, setLoading } = useLoading()
  const userStore = useUserStore()
  const loadings = ref(false)

  const loginConfig = useStorage('login-config', {
    rememberPassword: true,
    userName: '', // 演示默认值
    passWord: '', // demo default value
  })
  const userInfo = reactive({
    userName: loginConfig.value.userName,
    passWord: loginConfig.value.passWord,
    captcha: '',
  })

  const sendCode = reactive({
    codeText: '发送验证码',
    disable: false,
  })

  const state = reactive({
    color: {
      color1: '#40a1ff',
      color2: 'black',
      type: 1,
    },
    visible: false,
    current: 1,
    codeUrl: `/app/user/captcha`,
    passWord: '',
    forGot: {
      name: '发送验证码',
      post: '',
      codes: '',
      newPass: '',
      newPass1: '',
      Tips: '请保管好您的登录密码，切勿告知他人，以免造成您的财产损失',
    },
    phoneInfo: {
      phone: '',
      captcha: '',
    },
    loading: false,
  })
  // 验证密码是否一致
  const rules = [
    {
      validator: (value: string, cb: (arg0: string) => void) => {
        return new Promise<void>((resolve) => {
          if (value !== state.forGot.newPass) {
            cb('请确认两次密码是否一致')
          }
          resolve()
        })
      },
    },
  ]

  //忘记密码下一步
  const forgotNext = ({ errors }: { errors: Record<string, ValidatedError> | undefined }) => {
    if (!errors) {
      state.current = Math.min(3, state.current + 1)
    }
  }

  const beforeClose = () => {
    state.forGot = {
      name: '发送验证码',
      post: '',
      codes: '',
      newPass: '',
      newPass1: '',
      Tips: '请保管好您的登录密码，切勿告知他人，以免造成您的财产损失',
    }
    state.current = 1
  }

  //发动验证码
  const sends = () => {
    fotGot.value.validateField('post', (value: any) => {
      if (!value) {
        let time = 60
        const getPhoneInterval = setInterval(() => {
          sendCode.disable = true
          time--
          sendCode.codeText = time + 's重新发送'
          if (time <= 0) {
            clearInterval(getPhoneInterval)
            sendCode.codeText = '获取验证码'
            sendCode.disable = false
          }
        }, 1000)
      }
    })
  }

  //发动验证码
  const send = () => {
    phoneInfo.value.validateField('phone', (value: any) => {
      if (!value) {
        let time = 60
        const getPhoneInterval = setInterval(() => {
          sendCode.disable = true
          time--
          sendCode.codeText = time + 's重新发送'
          if (time <= 0) {
            clearInterval(getPhoneInterval)
            sendCode.codeText = '获取验证码'
            sendCode.disable = false
          }
        }, 1000)
      }
    })
  }
  console.log(window.location.pathname.split('/')[1])
  const onPrev = () => {
    state.current = Math.max(1, state.current - 1)
  }

  // const onNext = () => {
  //   state.current = Math.min(3, state.current + 1)
  // }

  const setCurrent = (current: number) => {
    state.current = current
  }

  const imgUrl = () => {
    state.codeUrl = `/app/user/captcha?timestamp=${new Date().getTime()}`
  }

  const handleClick = () => {
    state.visible = true
    state.current = 1
  }

  const handleCancel = () => {
    state.visible = false
  }

  const showImages = (val: number) => {
    if (val === 1) {
      state.color = {
        color1: '#40a1ff',
        color2: 'black',
        type: 1,
      }
    } else {
      state.color = {
        color2: '#40a1ff',
        color1: 'black',
        type: 2,
      }
    }
  }

  const logins = (data: any) => {
    data.passWord = userInfo.passWord
    state.loading = true
    formpost({
      url: userLogin,
      data: {
        userName: userInfo.userName,
        passWord: md5(userInfo.passWord),
        captcha: userInfo.captcha,
      },
    })
      .then((res) => {
        if (res.status) {
          // userStore.changeCommentlist(res.data.haveApi ? res.data.haveApi : [])
          state.loading = false
          // { data }: Response
          const obj = {
            nickName: '客户代理',
            userName: 'admin',
            userId: 1,
            roleId: 1,
            token: randomString(100),
          }
          userStore.saveUser(obj as UserState).then(() => {
            router
              .replace({
                path: '/children/home/monitor',
              })
              .then(() => {
                Message.success('登录成功，欢迎：' + userInfo.userName)
                loading.value = false
              })
          })
        }
      })
      .catch(() => {
        imgUrl()
        userInfo.captcha = ''
        state.loading = false
      })
  }

  const phoneLogins = (data: any) => {
    data.passWord = userInfo.passWord
    console.log(data)
    formpost({
      url: userLogin,
      data: {
        userName: userInfo.userName,
        passWord: md5(userInfo.passWord),
        captcha: userInfo.captcha,
      },
    })
      .then((res) => {
        userStore.changeCommentlist(res.data.haveApi ? res.data.haveApi : [])
        // { data }: Response
        const obj = {
          nickName: '客户代理',
          userName: 'admin',
          userId: 1,
          roleId: 1,
          token: randomString(100),
        }
        userStore.saveUser(obj as UserState).then(() => {
          router
            .replace({
              path: '/children/user/user',
            })
            .then(() => {
              Message.success('登录成功，欢迎：' + userStore.userName)
              loading.value = false
            })
        })
      })
      .catch(() => {
        loading.value = false
      })
  }

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined
    values: Record<string, any>
  }) => {
    if (!errors) {
      loadings.value = true
      setLoading(true)
      try {
        if (state.color.type == 1) {
          await logins(userInfo)
          const { rememberPassword } = loginConfig.value
          const { username, password } = values
          // 实际生产环境需要进行加密存储。
          // The actual production environment requires encrypted storage.
          loginConfig.value.userName = rememberPassword ? username : ''
          loginConfig.value.passWord = rememberPassword ? password : ''
        } else {
          await phoneLogins(phoneInfo)
          const { rememberPassword } = loginConfig.value
          const { username, password } = values
          // 实际生产环境需要进行加密存储。
          // The actual production environment requires encrypted storage.
          loginConfig.value.userName = rememberPassword ? username : ''
          loginConfig.value.passWord = rememberPassword ? password : ''
        }
      } catch (err) {
        errorMessage.value = (err as Error).message
        imgUrl()
      } finally {
        setLoading(false)
      }
    }
  }
  // const setRememberPassword = (value: boolean) => {
  //   loginConfig.value.rememberPassword = value;
  // };
</script>

<style lang="less" scoped>
  .imgs {
    width: 19px;
    height: 19px;
  }
  :deep(.arco-form-item) {
    margin-bottom: 25px;
  }
  :deep(.arco-input-prepend) {
    border: 0;
  }
  // :deep(.arco-tabs-nav-tab) {
  //   justify-content: center;
  // }
  :deep(.arco-tabs-nav-type-line .arco-tabs-tab-title) {
    padding: 16px 0;
    font-size: 16px;
    color: #000000;
  }
  :deep(.arco-tabs-tab-active) {
    color: #000000;
  }
  :deep(.arco-steps-item-process) {
    .arco-steps-item-title {
      color: #40a1ff;
    }
  }

  :deep(.arco-steps-item-process) {
    .arco-steps-item-description {
      color: #40a1ff;
    }
  }

  :deep(.arco-input-append) {
    padding: 0px;
    width: 120px;
  }

  .inputHeight {
    height: 40px;
  }

  .box {
    padding: 20px 0;
  }

  .code {
    width: 100%;
    height: 40px;
  }
  .login-form-wrapper {
    box-sizing: border-box;
    width: 433px !important;
    height: 470px;
    background: #ffffff;
    border-radius: 0 30px 30px 0;
    padding: 0;
    :deep(.arco-input-append) {
      padding: 0px;
    }

    .title {
      margin-bottom: 30px;
      font-size: 20px;
      .color {
        color: v-bind('state.color.color1');
        cursor: pointer;
      }
      .font {
        font-size: 15px;
        color: v-bind('state.color.color2');
        cursor: pointer;
      }
    }

    .name {
      margin: 0px 0 10px 0;
    }
  }
  .login-form {
    &-wrapper {
      width: 400px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
  :deep(.arco-form-item-status-error .arco-input-wrapper:not(.arco-input-disabled)) {
    margin-bottom: 0 !important;
  }
  :deep(.arco-form-item.arco-form-item-error, .arco-form-item.arco-form-item-has-help) {
    margin-bottom: 25px !important;
  }
  :deep(.arco-tabs-nav-type-line .arco-tabs-tab) {
    margin-left: 80px;
    margin-right: 0;
  }
</style>
